const { DataTypes } = require("sequelize");
const { sequelize } = require("../dbConnect");

// 成就定义表
const AchievementDefinition = sequelize.define('achievement_definitions', {
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true,
    comment: "成就定义ID"
  },
  key: {
    type: DataTypes.STRING(100),
    allowNull: false,
    unique: true,
    comment: "成就键值"
  },
  name: {
    type: DataTypes.STRING(100),
    allowNull: false,
    comment: "成就名称"
  },
  description: {
    type: DataTypes.TEXT,
    allowNull: true,
    comment: "成就描述"
  },
  icon: {
    type: DataTypes.STRING(200),
    allowNull: true,
    comment: "成就图标"
  },
  badge_color: {
    type: DataTypes.STRING(20),
    allowNull: true,
    comment: "徽章颜色"
  },
  category: {
    type: DataTypes.STRING(50),
    allowNull: true,
    comment: "成就分类"
  },
  type: {
    type: DataTypes.ENUM('count', 'score', 'time', 'streak', 'special'),
    allowNull: false,
    comment: "成就类型"
  },
  target_value: {
    type: DataTypes.INTEGER,
    allowNull: true,
    comment: "目标值"
  },
  points: {
    type: DataTypes.INTEGER,
    defaultValue: 0,
    comment: "奖励积分"
  },
  experience: {
    type: DataTypes.INTEGER,
    defaultValue: 0,
    comment: "奖励经验"
  },
  conditions: {
    type: DataTypes.JSON,
    allowNull: true,
    comment: "达成条件"
  },
  sort: {
    type: DataTypes.INTEGER,
    defaultValue: 0,
    comment: "排序"
  },
  is_active: {
    type: DataTypes.BOOLEAN,
    defaultValue: true,
    comment: "是否启用"
  }
}, {
  tableName: 'achievement_definitions',
  indexes: [
    {
      unique: true,
      fields: ['key']
    }
  ]
});

// 用户成就表
const UserAchievement = sequelize.define('user_achievements', {
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true,
    comment: "用户成就ID"
  },
  user_id: {
    type: DataTypes.INTEGER,
    allowNull: false,
    comment: "用户ID"
  },
  achievement_key: {
    type: DataTypes.STRING(100),
    allowNull: false,
    comment: "成就键值"
  },
  achievement_name: {
    type: DataTypes.STRING(100),
    allowNull: false,
    comment: "成就名称"
  },
  description: {
    type: DataTypes.TEXT,
    allowNull: true,
    comment: "成就描述"
  },
  icon: {
    type: DataTypes.STRING(200),
    allowNull: true,
    comment: "成就图标"
  },
  badge_color: {
    type: DataTypes.STRING(20),
    allowNull: true,
    comment: "徽章颜色"
  },
  points: {
    type: DataTypes.INTEGER,
    defaultValue: 0,
    comment: "获得积分"
  },
  experience: {
    type: DataTypes.INTEGER,
    defaultValue: 0,
    comment: "获得经验"
  },
  earned_at: {
    type: DataTypes.DATE,
    allowNull: false,
    defaultValue: DataTypes.NOW,
    comment: "获得时间"
  },
  progress: {
    type: DataTypes.JSON,
    allowNull: true,
    comment: "进度数据"
  }
}, {
  tableName: 'user_achievements',
  indexes: [
    {
      unique: true,
      fields: ['user_id', 'achievement_key']
    }
  ]
});

module.exports = {
  AchievementDefinition,
  UserAchievement
};
